package task

import (
	"io"
	"strings"
	"time"

	"github.com/PuerkitoBio/goquery"
)

type UpcomingContestInfoTask struct {
	TaskBase
}
type PastContestInfoTask struct {
	TaskBase
}
type contestInfo struct {
	Name   string
	Url    string
	Start  int64
	Length string
}

func trim(s string) string {
	s1 := strings.Trim(s, "\n")
	s2 := strings.Trim(s1, " ")
	s3 := strings.Trim(s2, "\n")
	s4 := strings.Trim(s3, " ")
	s5 := strings.Trim(s4, "\n")
	return s5
}
func (c UpcomingContestInfoTask) GetParseFunc(r io.Reader) interface{} {

	doc, err := goquery.NewDocumentFromReader(r)
	if err != nil {
		panic("parse html fail")
	}
	tables := doc.Find("table")
	upcomingContestTable := tables.Eq(0)
	trs := upcomingContestTable.Find("tr")
	upcContestInfoQue := make([]contestInfo, 0, 3)
	for i := 1; i < trs.Length(); i++ {
		ti, _ := time.Parse("Jan/02/2006 15:04", trim(trs.Eq(i).Find("td").Eq(2).Find("span").Text()))
		upcContestInfoQue = append(upcContestInfoQue, contestInfo{
			Name:   trim(trs.Eq(i).Find("td").Eq(0).Text()),
			Url:    "https://codeforces.com" + trs.Eq(i).Find("td").Eq(5).Find("a").Eq(0).AttrOr("href", ""),
			Start:  ti.UnixMilli(),
			Length: trim(trs.Eq(i).Find("td").Eq(3).Text()),
		})
	}
	return upcContestInfoQue

}

func (c PastContestInfoTask) GetParseFunc(r io.Reader) interface{} {

	doc, err := goquery.NewDocumentFromReader(r)
	if err != nil {
		c.SetErr(err)
		return ""
	}
	tables := doc.Find("table")
	upcomingContestTable := tables.Eq(1)
	trs := upcomingContestTable.Find("tr")
	upcContestInfoQue := make([]contestInfo, 0, 3)
	for i := 1; i < trs.Length(); i++ {
		ti, _ := time.Parse("Jan/02/2006 15:04", trim(trs.Eq(i).Find("td").Eq(2).Find("span").Eq(0).Text()))

		upcContestInfoQue = append(upcContestInfoQue, contestInfo{
			Name:   strings.Split(trim(trs.Eq(i).Find("td").Eq(0).Text()), "\n")[0],
			Url:    "https://codeforces.com" + trs.Eq(i).Find("td").Eq(0).Find("a").Eq(0).AttrOr("href", ""),
			Start:  ti.UnixMilli(),
			Length: trim(trs.Eq(i).Find("td").Eq(3).Text()),
		})
	}
	return upcContestInfoQue

}

func NewUpcomingContestInfoTask() ITask {
	return &UpcomingContestInfoTask{
		TaskBase{
			url:        "https://codeforces.com/contests",
			retryTimes: 3,
		},
	}
}

func NewPastContestInfo() ITask {
	return &PastContestInfoTask{
		TaskBase{
			url:        "https://codeforces.com/contests",
			retryTimes: 3,
		},
	}
}
